<?php
// +----------------------------------------------------------------------
// | Author: 发仔 <i@fazi.me> 
// +----------------------------------------------------------------------

namespace app\admin\controller;

use think\Config;
use think\Db;
use think\Hook;
use app\base\service\WechatPay;
use app\api\model;
class Order Extends Base
{
    protected $id    = 'order_id';
    protected $state = 'order_state';
    protected $table = 'order';
    protected $joins = [
        ['car c','c.car_id = m.car_id','left'],
        ['driver d','d.driver_id = m.driver_id','left'],
        ['car_type ct','ct.car_type_id = c.car_type_id','left'],
        ['car_type oct','oct.car_type_id = m.car_type_id','left'],
        ['order_fee of','of.order_id = m.order_id','left'],
        ['order_gps gps','gps.order_id = m.order_id','left'],
        ['order_fee fee','fee.order_id = m.order_id','left'],
        ['company com','com.company_id = m.company_id','left'],
    ];
    protected $field = 'm.*,
	    of.order_fee_id,of.pre_meter,of.pre_time,of.pre_fee,of.order_fee,of.wait_time,of.wait_fee,of.wait_fee2,of.start_fee,of.start_fee2,of.base_time,of.base_meter,of.use_time,of.time_fee,of.time_fee2,of.meter,of.travel_fee,of.remote_meter,of.remote_fee,of.remote_fee2,of.travel_fee2,of.low_speed_time,of.low_fee,of.low_fee2,of.night_meter,of.night_fee,of.night_fee2,of.high_fee,of.toll,of.park_fee,of.other_fee,of.other_note,of.cancel_time,of.cancel_fee,of.driver_money,of.passenger_money,of.company_money,of.order_money,of.discount,of.update_time,
	    c.register_time,ct.car_type_name,oct.car_type_name o_car_type_name,ct.type,c.number,d.name AS driver_name,d.phone AS driver_phone,gps.from_addr,gps.to_addr,fee.pre_time,fee.pre_fee,fee.pre_meter,gps.plan_time,gps.go_time,gps.arrival_time,fee.use_time,fee.passenger_money,com.company_name';

    //列表
    public function index() {

        $order_start = input('param.order_start');
        $order_end   = input('param.order_end');
        $driver_id   = input('param.driver_id');
        $passenger_id   = input('param.passenger_id');

        $where       = $this->search();
        if(isset($where['order_state']) && strpos($where['order_state'], '-') > 0 ) {
            $temp = array_unique(explode('-', $where['order_state']));
            $temp = array_filter($temp);
            if(!$temp) {
                unset($where['order_state']);
            }else {
                $where['order_state'] = array('IN', $temp);
            }
        }

        if(isset($where['order_state']) && $where['order_state'] === 'go'){
            $where['order_state'] = 7;
            $where['gps.go_time'] = ['GT', 0];
        }

        $order_states = config('base.order_states');
        // 调整顺序
        $temp = $order_states[8];
        $order_states[8] = ['key' => 'go', 'name' => '执行中'];
        $order_states[9] = $temp;
        $order_states[10] = ['key' => '9-10-11', 'name' => '已完成'];
        unset($order_states[11]);

        $order_start && $where['order_time'][] = ['>=',$order_start];
        $order_end && $where['order_time'][] = ['<=',$order_end];
        $driver_id && $where['m.driver_id'] = ['=',$driver_id];
        $passenger_id && $where['m.passenger_id'] = ['=',$passenger_id];

        if(isset($where['order_state']) && $where['order_state'] === '7'){
            $list = $this->joins()->where($where)->whereNull('m.delete_time')->whereNull('gps.go_time')->order('m.order_time DESC')->fetchSql(0)->paginate(10,false,[
                'query' => input('param.')
            ]);
        }else{
            $list = $this->joins()->where($where)->whereNull('m.delete_time')->order('m.order_time DESC')->fetchSql(0)->paginate(10,false,[
                'query' => input('param.')
            ]);
        }


        $this->assign('list',$list);
        $this->assign('pager',$list->render());
        $this->assign('order_states', $order_states);
        $this->assign('op', input('param.op', null, 'trim'));
        $this->assign('company_id', input('param.company_id', null, 'trim'));
        return $this->out();

    }

    //搜索
    protected function search() {
        //搜索
        $where = [];
        $P = input('param.');
        $P['order_no'] && $where['order_no'] = ['like', '%'.$P['order_no'].'%'];
        $P['passenger_name'] && $where['m.passenger_name'] = ['like', '%'.$P['passenger_name'].'%'];
        $P['passenger_phone'] && $where['m.passenger_phone'] = ['like', '%'.$P['passenger_phone'].'%'];
        $P['order_type'] && $where['order_type'] = $P['order_type'];
        $P['order_state'] && $where['order_state'] = $P['order_state'];
        $P['company_id'] && $P['company_id'] > 0 && $where['m.company_id'] = $P['company_id'];

        //公务只能看公务订单
        if( $this->user['official'] ){
            $where['order_type'] = 1;
//			$where['ct.type'] = ['in','2,3'];
        }
        //乘客
        if($P['car_use_id']) {
            $this->joins[] = ['passenger p','p.passenger_id = m.passenger_id'];
            $this->joins[] = ['car_use cu','p.car_use_id = cu.car_use_id'];
            $where['cu.car_use_id'] = $P['car_use_id'];
        }

        $this->options($where);

        //弹出层搜索
        $op = input('param.op');
        if(in_array($op, ['search','bind','unbind']) ) {
            $this->assign('notPopup',0);
        }
        $this->assign('op',$op);

        return $where;

    }

    public function detail() {

//		$this->field .= ',cu.name AS car_use_name';
//		$this->joins[] = ['passenger p','p.passenger_id = m.passenger_id','left'];
//		$this->joins[] = ['car_use cu','cu.car_use_id = p.car_use_id','left'];


//		$item = $this->joins()->where('m.'.$this->id,$id)->find();

//		halt($item);

        $id = input('param.'.$this->id);
        list($code,$data)= (new \app\adminapi\model\Order())->orderList('*', ['order_id' => $id], 1, 1);
        $order = $data['data'][0];
        $order = $order->toArray();

        $structures = Config::get('base.structures');
        $booking_types = Config::get('base.booking_types');
        $order_types = Config::get('base.order_types');
        $use_types = Config::get('base.use_types');
        $pay_types = Config::get('base.pay_types');

        $order['structure_name'] = $structures[ intval($order['structure']) ];
        $order['booking_type_name'] = $booking_types[ intval($order['booking_type']) ];
        $order['order_type_name'] = $order_types[ intval($order['order_type']) ];
        $order['use_type_name'] = $use_types[ intval($order['use_type']) ];
        $order['pay_type_name'] = $pay_types[ intval($order['pay_type']) ];

//        halt($order);
        $this->assign('order',$order);
        return $this->out();

    }

    //派车
    public function dispatch() {


        if(request()->isPost()){

            $data = [];
            $data['driver_id'] = input('post.driver_id', '', 'intval');
            $data['car_id'] = input('post.car_id', '', 'intval');
            $data['order_state'] = input('post.order_state', '', 'intval');

            $oid = input('param.order_id', '', 'intval');

            $err = null;
            if(!(int)$data['driver_id']){
                $err = '请选择司机';
                return $this->res(false, $err);
            }

            if(!(int)$data['car_id']){
                $err = '请选择车辆';
                return $this->res(false, $err);
            }

            if(!(int)$oid){
                $err = '非法操作';
                return $this->res(false, $err);
            }

            $redispatch = input('post.redispatch', 0, 'intval');
            $redispatch = $redispatch ? 1 : 0;

            $order = Db::name('order')->where('order_id',$oid)->find();
            if(!$redispatch && $order['order_state'] >= 5) {
                return $this->res(false, '该订单已派车，如需改派，请刷新页面后重试');
            }

            $result = (new \app\api\logic\Driver())->receiveOrder($data['driver_id'], $oid, $data['car_id'], 2, $redispatch, true);
            if($result[0]){
                return $this->res(true,'派车成功',url('order/detail',['order_id'=>$oid]));
            }

            return $this->retAll($result[0], $result[1]);

//			$rslt = Db::name('order')->where('order_id',$oid)->update($data);
//			$rslt && Hook::listen('send_order',$oid);
//			//TODO 绑定用车方法
//            // 修改司机状态
//            $driverData['work_state'] = 1;
//            Db::name('driver')->where('driver_id')->update($driverData);
//            // 增加派单记录
//            (new \app\api\logic\Order())->addDispatchLog($oid,$data['driver_id'],$data['car_id'],1);
//			return $this->res($rslt,'派车成功',url('order/detail',['order_id'=>$oid]));
        }

        return $this->detail();
    }

    //改派
    public function redispatch() {



        $P = input('post.');
        if($P) {
            $oid = input('param.order_id');
//			Hook::listen('send_order',$oid);
            $order = Db::name('order')->find($oid);
            if(!$order){
                return $this->res(false, '订单不存在');
            }

            $params = [
                'oid' => $oid,
                'driver_id' => $order['driver_id'],
            ];
            $rslt = Db::name('order')->where('order_id',$oid)->update($P);

            if($rslt){
                Hook::listen('change_dispatch',$params);
            }else{
                return $this->res(false, '司机与车辆未更改，订单未改派');
            }

            return $this->res($rslt);
        }

        return false;
    }



    public function stat() {


        $start = input('param.start','1970-01-01');
        $end = input('param.end',date('Y-m-d'));
        $time = input('param.time','year');

        $start = $start ?: '1970-01-01';
        $end = $end ?: date('Y-m-d');

        if($time == 'day') {
            $start = date('Y-m-d');
        } elseif($time == 'month') {
            $start = date('Y-m-01');
        } elseif($time == 'year') {
            $start = date('Y-01-01');
        }

        $types = config('base.use_types');

        //所有订单分析
        $list = Db::name('order')->alias('o')->join('order_fee of','of.order_id = o.order_id')->where('order_time','>=',$start)->where('order_time','<=',$end)->fetchSql(0)->field('o.use_type,of.order_money,of.use_time')->select();

//        halt($list);

        $qty = $price = $time = [];

//		halt(array_column($list,'use_type'));

        foreach($list AS $order) {

            if(in_array($order['use_type'],array_keys($types))) {
                //订单数
                $qty[$order['use_type']]++;
                $price[$order['use_type']] += $order['order_money'];
                $time[$order['use_type']] += $order['use_time'];
            }


        }
        $this->assign('types',$types);
        $this->assign('qty',$qty);
        $this->assign('price',$price);
        $this->assign('time',$time);

        return $this->out();
    }

    protected function options($item = []) {

        //公务只能看公务订单
        $order_types = config('base.order_types');
        if( $this->user['official'] ){
            $order_types = false;
        }

        $this->assign('order_types',$order_types);
        return $item;
    }

    /**
     * 获取轨迹
     * @return json
     */
    public function getTrack(){
        $oid = input('oid',0);
        return (new \app\api\model\Order())->getTrack($oid);
    }


    //下单
    public function add_order(){
        $P = input('param.');

        if($P['is_return'] == '1'){//是否返程,接口文档和数据库文档不一致,可能需要讨论
            $P['is_return'] = '0';
        }
        elseif ($P['is_return'] == '9'){
            $P['is_return'] = '1';
        }
        $data = array(
            'passenger_name' => $P['passenger_name'],//乘客姓名
            'passenger_id' => $P['passenger_id'],//乘客ID
            'passenger_phone' => $P['passenger_phone'],//乘客电话
            'orderer' => $P['orderer_name'],//下单人姓名
            //'orderer_id' => $P['orderer_id'],//下单人ID
            'approval' => $P['approval_name'],//审批人
            'approval_id' => $P['approval_id'],//审批人ID
            'booking_type' => $P['booking_type'],//订车类型
            //'car_type_id' => $P['car_type_id'],//车辆类型
            'order_type' => $P['order_type'],//订单类型
            'use_type' => $P['use_type'],//用车类型
            'pay_type' => $P['pay_type'],//支付方式
            'departure' => $P['from_addr'],//出发地
            'departure_coord' => $P['from_lat'].','.$P['from_lon'],//出发地坐标
            'destination' => $P['to_addr'],//目的地
            'destination_coord' => $P['to_lat'].','.$P['to_lon'],//目的地坐标
            'appointment_time' => $P['used_time'],//预计时间
            //'pre_fee' => $P['pre_fee'],//预计费用
            'estimate_mileage' => $P['estimate_mileage'],//预计距离
            'is_return' => $P['is_return'],//是否往返
            'order_state' => $P['order_state'],//订单状态
            'apply_time' => date('Y-m-d h:i:s'),//申请时间
        );

        $data['order_no'] = (new \app\api\logic\Order())->createSn();

        $order_return = Db::name('order')->insertGetId($data);

        if($P['order_state']==1 && $order_return){
            $result = array(
                'code' => '1',
                'data' => array('order_id' => $order_return,'type' => '智能化派车')
            );
            return json_encode($result);
        }
        elseif ($P['order_state']==2 && $order_return){
            $result = array(
                'code' => '1',
                'data' => array('order_id' => $order_return,'type' => '手动派车')
            );
            return json_encode($result);
        }
        elseif ($P['order_state']==3 && $order_return){
            $result = array(
                'code' => '1',
                'data' => array('order_id' => $order_return,'type' => '跨域派车')
            );
            return json_encode($result);
        }
    }

    //状态
    public function state() {

        $id = input('post.id/d');
        $state = input('post.state/d');

        if($id) {

            $order = Db::name($this->table)->find($id);

            // 取消订单
            if($state === 12 && $order){
                $result =  (new \app\api\model\Order())->cancelOrder($order['order_id'], $order['order_no'], $order['passenger_id'], false, true);
                return $this->retAll($result[0], $result[1]);
            }

            $key = $this->state ?: 'state';
            $rslt = Db::name($this->table)->where($this->id,$id)->fetchSql(0)->setField($key,$state);

        }

        return $this->res($rslt);

    }

    //免单 2018-08-27 BY 发仔
    public function setFree()
    {
        $rslt = false;

        $oid = input('param.oid');
        $order = (new \app\api\model\Order())->get($oid);
        if($order && $order->order_state == 9) {
            //状态更新到待评价
            $order->order_state = 10;
            $order->free_admin_id = $this->user['user_id'];
            $rslt = $order->isUpdate()->allowField('order_state,free_admin_id')->save();
        }

        return $this->res($rslt);
    }
    //应急支付 2018-08-27 BY 发仔
    public function adminOrderPay() {

        $oid = input('param.oid');
        $order = (new model\Order())->get($oid);
//		$pid   = $this->passengerInfo['passenger_id'];
//		if (!$order || $order->passenger_id != $pid) {
//			return $this->retError(404);
//		}
        if ($order->order_state != 9) {
            return $this->retError('该订单尚未完成');
        }
        $fee      = model\OrderFee::get(['order_id' => $oid]);
        $money    = $fee->passenger_money ? floatval($fee->passenger_money) : 0;
        $payType  = $order->pay_type;
        list($code,$leftPay) = (new model\Passenger())->orderPay($oid,$pid,$money,$payType);
        if($code==1){
            Hook::listen('pay_order',$oid);
            return $this->retSucc();
        }else{
            $money = floatval($leftPay)*100;
            if($money==0){
                return $this->retError('额度不足');
            }
            list($code, $data) = (new WechatPay())->makeWeChatPay('订单支付',  '晋江出行', $order->order_no, $money);
            return $this->retAll($code,$data);
        }
    }

    //从司机管理弹出的订单查询
    public function lookOrder() {
//        $driver_id = input('param.driver_id');
        $where = [];
        input('param.driver_id') && $where['m.driver_id'] = ['=', input('param.driver_id')];
        input('param.passenger_id') && $where['m.passenger_id'] = ['=', input('param.passenger_id')];
        $order_return = Db::name('order')
            ->alias('m')
            ->where($where)
            ->join('car c','c.car_id = m.car_id','left')
            ->join('driver d','d.driver_id = m.driver_id','left')
            ->join('car_type ct','ct.car_type_id = c.car_type_id','left')
            ->join('car_type oct','oct.car_type_id = m.car_type_id','left')
            ->join('order_fee of','of.order_id = m.order_id','left')
            ->join('order_gps gps','gps.order_id = m.order_id','left')
            ->join('order_fee fee','fee.order_id = m.order_id','left')
            ->join('company com','com.company_id = m.company_id','left')
            ->whereNull('m.delete_time')
            ->order('m.order_time DESC')
            ->field('m.*,
	    of.order_fee_id,of.pre_meter,of.pre_time,of.pre_fee,of.order_fee,of.wait_time,of.wait_fee,of.wait_fee2,of.start_fee,of.start_fee2,of.base_time,of.base_meter,of.use_time,of.time_fee,of.time_fee2,of.meter,of.travel_fee,of.remote_meter,of.remote_fee,of.remote_fee2,of.travel_fee2,of.low_speed_time,of.low_fee,of.low_fee2,of.night_meter,of.night_fee,of.night_fee2,of.high_fee,of.toll,of.park_fee,of.other_fee,of.other_note,of.cancel_time,of.cancel_fee,of.driver_money,of.passenger_money,of.company_money,of.order_money,of.discount,of.update_time,
	    c.register_time,ct.car_type_name,oct.car_type_name o_car_type_name,ct.type,c.number,d.name AS driver_name,d.phone AS driver_phone,gps.from_addr,gps.to_addr,fee.pre_time,fee.pre_fee,fee.pre_meter,gps.plan_time,gps.go_time,gps.arrival_time,fee.use_time,fee.passenger_money,com.company_name')
            ->fetchSql(0)
            ->paginate(10,false,[
                'query' => input('param.')
            ]);
        $this->assign('list',$order_return);
        $this->assign('pager',$order_return->render());
        $this->assign('notPopup',0);//不需要侧边栏
        return $this->out();

    }

}